<template>
    <div id="ShopCart">
        <el-row>
            <el-col :span="12">
                <el-input
                    placeholder="请输入内容"
                    v-model="param.key"
                    clearable>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="info" icon="el-icon-search" @click="getCartList()">搜索</el-button>
            </el-col>
        </el-row>
        <el-table class="" ref="buyerTable" border stripe tooltip-effect="dark" style="width: 100%" height="650" border
                  :data="shopcartlist" @selection-change="handleSelectionChange" :row-key="getkey">
            <!--选择框，可以多选 -->
            <el-table-column type="selection"  :reserve-selection="true">
            </el-table-column>
            <el-table-column label="店铺" prop="shop_name" header-align="center"   />
            <el-table-column label="商品名称" prop="goods_name" header-align="center"   />
            <el-table-column label="图片"  align="center">
                <template slot-scope="scope">
                        <el-image style="width: 120px; height: 90px"  fit="cover" :src="scope.row.goods_img"  />
                </template>
            </el-table-column>
            <!--  商品单价          -->
            <el-table-column label="单价"  prop="price" header-align="center" align="right">
                <template slot-scope="scope">
                    <div>￥{{ (scope.row.price / scope.row.count).toFixed(2)}}</div>
                </template>
            </el-table-column>
            <!--商品数量            -->
            <el-table-column label="数量" prop="count"  header-align="center">
                <template slot-scope="scope">
                    <div class="count-warp">
                        <input class="border" @input="cartGoodscountChange($event,scope.row)"
                               v-model="scope.row.count" />
                        <div class="quick-button">
                            <i class="border el-icon-arrow-up" @click="addcountCount(scope.row)"></i>
                            <i class="border el-icon-arrow-down" @click="subtractcountCount(scope.row)"></i>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <!--商品总价            -->
            <el-table-column label="小计"  header-align="center" align="right">
                <template slot-scope="scope">
                    <div>￥{{ (scope.row.price ).toFixed(2) }}</div>
                    <!--4舍5入        -->
                </template>
            </el-table-column>
            <!--单个删除            -->
            <el-table-column label="操作"  align="center">
                <template slot-scope="scope">
                        <el-button size="mini" type="danger" icon="el-icon-delete"
                                   @click="deleteCartGoods(scope.row)" />
                </template>
            </el-table-column>
        </el-table>
        <!-- 多个删除       -->
        <div class="cart-option">
            <el-button type="danger" @click="batchDeleteCartGoods">删除选中商品</el-button>
            <div class="other-info">
                <div class="common">已选择<span class="total-num">{{this.multipleSelection.length}}</span>件商品
                </div>
                <div class="common">总价(不含运费):<span class="total-price">￥{{cartTotalPrice}}元</span></div>
                <el-button type="danger" @click="make_order">去支付</el-button>
            </div>
        </div>
        <!-- 分页器 -->
    </div>

</template>
<script>
export default {
    data() {
        return {
            param:{
                key:"",
                userid:window.sessionStorage.getItem('userid'),
            },
            shopcartlist: [],
            ///多选中选中的行的数组
            multipleSelection: [],
            single_del_param:{
                userid:window.sessionStorage.getItem('userid'),
                goods_id:-1,
            },
            all_del_param:{
                userid:window.sessionStorage.getItem('userid'),
                goods_id:[],
            },
            update_param:{
                userid:window.sessionStorage.getItem('userid'),
                goods_id:-1,
                count:0,
            },
            makeorder_param:{
                username:window.sessionStorage.getItem('username'),
                userid:window.sessionStorage.getItem('userid'),
                totalAmout:-1,
                totalNum:-1,
                create_time:0,
                goods_id:[],
            },
        }
    },
    created() {
        this.getCartList();
    },
    methods: {
        // 获取购物车列表（这个要在created里面调用）
        getCartList() {
            this.$ajax.get(this.$API.http+"/api/Usershopcart/query", {params:this.param}).then(res=> {
                    this.msg = res.data.msg;
                    if(res.data.code == 1){
                        this.shopcartlist = res.data.data
                        console.log(this.shopcartlist);
                    }
                    else{
                        this.$msg.error(this.msg);
                    }
                },
                error => {
                    //请求后更新List的数据
                    window.alert(error);
                }
            )

        },
        ///多选功能，是否选中
        handleSelectionChange(val) {
            // console.log(val);
            this.multipleSelection = val;
            console.log(this.multipleSelection.length);
            console.log(this.multipleSelection);
        },
        // 商品数量文本框改变事件
        cartGoodscountChange(e, orderInfo) {
            if (e.target.value <= 0) {
                orderInfo.count = 1
                this.$msg.error('商品数量不能小于0')
            }
        },
        // 商品数量加1
        addcountCount(orderInfo) {
            this.update_param.goods_id =  orderInfo.goods_id;
            this.update_param.count = orderInfo.count+1;
            this.$ajax.get(this.$API.http+"/api/Usershopcart/update", {params:this.update_param}).then(res=> {
                    this.msg = res.data.msg;
                    if(res.data.code == 1){
                        //查询数据库更新操作
                        ++orderInfo.count;
                        this.$msg.success(this.msg);
                        this.getCartList();
                    }
                    else{
                        this.$msg.error(this.msg);
                    }
                },
                error => {
                    //请求后更新List的数据
                    window.alert(error);
                }
            )
        },
        // 商品数量减1
        subtractcountCount(orderInfo) {
            //查询数据库更新操作
            if (orderInfo.count <= 1) {
                return this.$msg.error('商品数量不能小于0')
            }
            this.update_param.goods_id =  orderInfo.goods_id;
            this.update_param.count = orderInfo.count-1;
            this.$ajax.get(this.$API.http+"/api/Usershopcart/update", {params:this.update_param}).then(res=> {
                    this.msg = res.data.msg;
                    if(res.data.code == 1){
                        this.$msg.success(this.msg);
                        --orderInfo.count;
                        this.getCartList();
                    }
                    else{
                        this.$msg.error(this.msg);

                    }
                },
                error => {
                    //请求后更新List的数据
                    window.alert(error);
                }
            )
        },
        // 单个删除购物车商品
        deleteCartGoods(row) {
            // console.log(row);
            this.single_del_param.goods_id = row.goods_id;
            this.$confirm('此操作将移除购物车的商品, 是否继续?', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
            }).then(()=>{
                    this.$ajax.get(this.$API.http+"/api/Usershopcart/del", {params:this.single_del_param}).then(res=> {
                            this.msg = res.data.msg;
                            if(res.data.code == 1){
                                this.getCartList();
                            }
                            else{
                                this.$msg.error(this.msg);
                            }
                        },
                        error => {
                            //请求后更新List的数据
                            window.alert(error);
                        }
                    )
                }
            ).catch((e) => {
                console.log(e)
                this.$msg.info('已取消删除')
            })
        },
        // 批量删除购物车商品
        batchDeleteCartGoods() {
            if (this.multipleSelection.length > 0) {

            } else {
                return this.$msg.error('请勾选要移除购物车的商品')
            }
            this.$confirm('此操作将移除勾选的购物车的商品, 是否继续?', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
            }).then(() => {
                this.all_del_param.goods_id = this.multipleSelection.map((item, index)=>{
                    return item.goods_id;
                });
                this.$ajax.get(this.$API.http+"/api/Usershopcart/delall", {params:{"userid":this.all_del_param.userid, "goods_id":this.all_del_param.goods_id}}).then(res=> {
                        this.msg = res.data.msg;
                        if(res.data.code == 1){
                            this.getCartList();
                        }
                        else{
                            this.$msg.error(this.msg);
                        }
                    },
                    error => {
                        //请求后更新List的数据
                        window.alert(error);
                    }
                )
                // 这里调用接口删除的方法
            }).catch((e) => {
                console.log(e)
                this.$msg.info('已取消删除')
            })
        },
        //  区分不同行
        getkey(row) {
            //row.id的id必须存在并且是唯一的值
            return row.id;
            console.log(row.id);
        },
        make_order(){
            this.makeorder_param.totalAmout = this.cartTotalPrice;
            this.makeorder_param.totalNum = this.multipleSelection.length;
            this.makeorder_param.create_time =new Date().getTime();   //获取当前时间戳;
            this.makeorder_param.goods_id = this.multipleSelection.map((item, index)=>{
                return item.goods_id;
            });
            this.$ajax.get(this.$API.http+"/api/Usershopcart/order", {params:this.makeorder_param}).then(res=> {
                    this.msg = res.data.msg;
                    if(res.data.code == 1){
                        this.$msg.success(this.msg);
                        this.getCartList();
                        this.multipleSelection = [];
                    }
                    else{
                        this.$msg.error(this.msg);
                    }
                },
                error => {
                    //请求后更新List的数据
                    window.alert(error);
                }
            )
        }
    },
    computed: { //存在缓存，建议不经常的变化的在次操作
        //计算总价
        cartTotalPrice() {
            let sum = 0
            this.multipleSelection.forEach(item => {
                sum += item.price
            })
            // 因为要保留小数点后面两位，所以要toFixed(2)
            return sum.toFixed(2);
            // return 0.0;
        },
    }
}
</script>

<style scoped>

</style>
